import React, { useEffect, useState } from 'react';
import { Card, Row, Col, Statistic, Typography, Table, Tag, Button, message, Skeleton, Avatar, Badge, Progress, Tooltip, Divider } from 'antd';
import { 
  MessageOutlined, 
  UserOutlined, 
  LinkOutlined, 
  ClockCircleOutlined,
  CheckCircleOutlined,
  SyncOutlined,
  ExclamationCircleOutlined,
  LogoutOutlined,
  PieChartOutlined,
  TeamOutlined,
  AreaChartOutlined,
  UpOutlined,
  DownOutlined,
  ShopOutlined,
  RightOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import api from '../services/api';
import { LineChart, Line, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip as RechartsTooltip, ResponsiveContainer } from 'recharts';

const { Title, Paragraph, Text } = Typography;

const Dashboard = () => {
  const [stats, setStats] = useState({
    totalContacts: 0,
    totalChats: 0,
    messagesReceivedToday: 0,
    messagesSentToday: 0,
    connectionStatus: 'disconnected',
    responseRate: 0,
    avgResponseTime: 0,
    crmCustomers: 0,
    contactsIncrease: 0,
    messagesIncrease: 0
  });
  const [recentContacts, setRecentContacts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [activityData, setActivityData] = useState([]);
  const [contactTrends, setContactTrends] = useState([]);
  const { user, logout } = useAuth();
  const navigate = useNavigate();

  useEffect(() => {
    // 从API获取真实数据
    const fetchDashboardData = async () => {
      try {
        setLoading(true);
        const response = await api.get('/reports/user-dashboard');
        
        // 更新统计数据
        setStats({
          totalContacts: response.data.totalContacts || 0,
          totalChats: response.data.totalChats || 0,
          messagesReceivedToday: response.data.messagesReceivedToday || 0,
          messagesSentToday: response.data.messagesSentToday || 0,
          connectionStatus: response.data.connectionStatus || 'disconnected',
          responseRate: response.data.responseRate || 0,
          avgResponseTime: response.data.avgResponseTime || 0,
          crmCustomers: response.data.crmCustomers || 0,
          contactsIncrease: response.data.contactsIncrease || 0,
          messagesIncrease: response.data.messagesIncrease || 0
        });
        
        // 更新联系人数据
        setRecentContacts(response.data.recentContacts || []);
        
        // 更新活动数据
        if (response.data.activityData) {
          setActivityData(response.data.activityData);
        } else {
          // 如果API中没有图表数据，生成模拟数据用于展示
          generateMockData();
        }
      } catch (error) {
        console.error('获取仪表盘数据失败:', error);
        message.error('获取仪表盘数据失败，请稍后再试');
        
        // 设置默认数据（如果API失败）
        setStats({
          totalContacts: 0,
          totalChats: 0,
          messagesReceivedToday: 0,
          messagesSentToday: 0,
          connectionStatus: 'disconnected',
          responseRate: 0,
          avgResponseTime: 0,
          crmCustomers: 0,
          contactsIncrease: 0,
          messagesIncrease: 0
        });
        setRecentContacts([]);
        
        // 生成模拟数据用于展示
        generateMockData();
      } finally {
        setLoading(false);
      }
    };
    
    const generateMockData = () => {
      // 生成过去7天的模拟活动数据
      const mockActivityData = [];
      const mockContactTrends = [];
      
      for (let i = 6; i >= 0; i--) {
        const date = new Date();
        date.setDate(date.getDate() - i);
        const dateStr = date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
        
        mockActivityData.push({
          date: dateStr,
          sent: Math.floor(Math.random() * 50) + 10,
          received: Math.floor(Math.random() * 40) + 5,
        });
        
        mockContactTrends.push({
          date: dateStr,
          active: Math.floor(Math.random() * 20) + 5,
          new: Math.floor(Math.random() * 5) + 1,
        });
      }
      
      setActivityData(mockActivityData);
      setContactTrends(mockContactTrends);
    };
    
    fetchDashboardData();
  }, []);

  // 处理退出登录
  const handleLogout = () => {
    logout();
    navigate('/login');
  };

  // 表格列定义
  const columns = [
    {
      title: '联系人',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Avatar 
            style={{ 
              marginRight: 8, 
              backgroundColor: record.unread ? '#1890ff' : '#f0f0f0',
              backgroundImage: record.avatar ? `url(${record.avatar})` : 'none',
              backgroundSize: 'cover'
            }}
          >
            {!record.avatar && text.charAt(0)}
          </Avatar>
          <div>
            <Button 
              type="link" 
              onClick={() => navigate(`/chat/${record.id}`)}
              style={{ padding: '0', height: 'auto', fontWeight: record.unread ? 'bold' : 'normal' }}
            >
              {text}
            </Button>
            {record.status && (
              <div>
                <Badge 
                  status={record.status === 'online' ? 'success' : 'default'} 
                  text={<Text type="secondary" style={{fontSize: '12px'}}>{record.status === 'online' ? '在线' : record.lastSeen || '离线'}</Text>} 
                />
              </div>
            )}
          </div>
          {record.unread > 0 && (
            <Badge count={record.unread} style={{ marginLeft: 8 }} />
          )}
        </div>
      )
    },
    {
      title: '最近消息',
      dataIndex: 'lastMessage',
      key: 'lastMessage',
      ellipsis: true,
      render: (text, record) => (
        <div>
          {record.hasSensitive && <Tag color="error">敏感</Tag>}
          {record.isCrmCustomer && <Tag color="processing">CRM</Tag>}
          <Text ellipsis style={{ maxWidth: 250 }}>{text}</Text>
        </div>
      )
    },
    {
      title: '时间',
      dataIndex: 'time',
      key: 'time',
      width: 100,
      render: time => (
        <Text type="secondary">
          <ClockCircleOutlined style={{ marginRight: 4 }} />
          {time}
        </Text>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 160,
      render: (_, record) => (
        <div>
          <Button 
            type="primary" 
            size="small" 
            icon={<MessageOutlined />}
            onClick={() => navigate(`/chat/${record.id}`)}
            style={{ marginRight: 8 }}
          >
            聊天
          </Button>
          {!record.isCrmCustomer && (
            <Tooltip title="添加到CRM">
              <Button
                size="small"
                icon={<ShopOutlined />}
                onClick={() => navigate(`/crm/add/${record.id}`)}
              />
            </Tooltip>
          )}
        </div>
      )
    }
  ];

  // 获取连接状态组件
  const getConnectionStatusContent = () => {
    const statusMap = {
      connected: { 
        color: '#52c41a', 
        icon: <CheckCircleOutlined />, 
        text: '已连接',
        description: '您的WhatsApp已连接，可以收发消息。'
      },
      connecting: { 
        color: '#faad14', 
        icon: <SyncOutlined spin />, 
        text: '连接中',
        description: '正在连接到您的WhatsApp，请稍候...'
      },
      disconnected: { 
        color: '#ff4d4f', 
        icon: <ExclamationCircleOutlined />, 
        text: '未连接',
        description: '请连接您的WhatsApp以开始使用。'
      }
    };
    
    const status = statusMap[stats.connectionStatus] || statusMap.disconnected;
    
    return (
      <div style={{ display: 'flex', alignItems: 'center' }}>
        <div style={{ 
          fontSize: 24, 
          marginRight: 16,
          color: status.color
        }}>
          {status.icon}
        </div>
        <div>
          <div style={{ fontWeight: 'bold' }}>{status.text}</div>
          <div style={{ fontSize: 12, color: '#888' }}>{status.description}</div>
        </div>
      </div>
    );
  };

  return (
    <div className="dashboard-container">
      <div className="dashboard-header" style={{ marginBottom: 24 }}>
        <div>
          <Title level={2} style={{ margin: '0 0 8px 0' }}>欢迎回来, {user?.fullName || user?.username || '用户'}</Title>
          <Paragraph className="dashboard-subtitle" style={{ margin: 0, opacity: 0.7 }}>查看您的最新统计数据和活动情况</Paragraph>
        </div>
        <div style={{ display: 'flex', gap: '10px' }}>
          <Button type="primary" icon={<LinkOutlined />} onClick={() => navigate('/connect')}>
            管理WhatsApp连接
          </Button>
          <Button 
            type="primary" 
            danger 
            icon={<LogoutOutlined />} 
            onClick={handleLogout}
          >
            退出登录
          </Button>
        </div>
      </div>
      
      {/* 统计卡片 */}
      <Row gutter={[16, 16]} className="stats-row">
        <Col xs={12} sm={12} md={6}>
          <Card className="stats-card" loading={loading} bordered={false} style={{boxShadow: '0 2px 8px rgba(0,0,0,0.08)'}}>
            <Statistic
              title={
                <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
                  <span>联系人总数</span>
                  <Text type={stats.contactsIncrease >= 0 ? "success" : "danger"}>
                    {stats.contactsIncrease > 0 ? <UpOutlined /> : <DownOutlined />}
                    {Math.abs(stats.contactsIncrease)}%
                  </Text>
                </div>
              }
              value={stats.totalContacts}
              prefix={<UserOutlined className="stats-icon" style={{backgroundColor: '#e6f7ff', padding: '8px', borderRadius: '8px', color: '#1890ff'}} />}
              valueStyle={{ color: '#1890ff', fontWeight: 'bold' }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={12} md={6}>
          <Card className="stats-card" loading={loading} bordered={false} style={{boxShadow: '0 2px 8px rgba(0,0,0,0.08)'}}>
            <Statistic
              title={
                <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
                  <span>聊天总数</span>
                  <Text type={stats.messagesIncrease >= 0 ? "success" : "danger"}>
                    {stats.messagesIncrease > 0 ? <UpOutlined /> : <DownOutlined />}
                    {Math.abs(stats.messagesIncrease)}%
                  </Text>
                </div>
              }
              value={stats.totalChats}
              prefix={<MessageOutlined className="stats-icon" style={{backgroundColor: '#f9f0ff', padding: '8px', borderRadius: '8px', color: '#722ed1'}} />}
              valueStyle={{ color: '#722ed1', fontWeight: 'bold' }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={12} md={6}>
          <Card className="stats-card" loading={loading} bordered={false} style={{boxShadow: '0 2px 8px rgba(0,0,0,0.08)'}}>
            <Statistic
              title={<span>今日消息 (接收/发送)</span>}
              value={stats.messagesReceivedToday + stats.messagesSentToday}
              valueStyle={{ color: '#13c2c2', fontWeight: 'bold' }}
              suffix={<small style={{ fontSize: '14px', color: '#999' }}>条</small>}
            />
            <div style={{ marginTop: 8 }}>
              <Text type="secondary" style={{ fontSize: 12 }}>接收: {stats.messagesReceivedToday}</Text>
              <Divider type="vertical" />
              <Text type="secondary" style={{ fontSize: 12 }}>发送: {stats.messagesSentToday}</Text>
            </div>
          </Card>
        </Col>
        <Col xs={12} sm={12} md={6}>
          <Card className="stats-card" loading={loading} bordered={false} style={{boxShadow: '0 2px 8px rgba(0,0,0,0.08)'}}>
            <Statistic
              title="CRM客户数"
              value={stats.crmCustomers}
              prefix={<ShopOutlined className="stats-icon" style={{backgroundColor: '#fff2e8', padding: '8px', borderRadius: '8px', color: '#fa541c'}} />}
              valueStyle={{ color: '#fa541c', fontWeight: 'bold' }}
            />
            <div style={{ marginTop: 8 }}>
              <Button type="link" size="small" onClick={() => navigate('/crm')} style={{ padding: 0 }}>
                管理CRM客户 <RightOutlined />
              </Button>
            </div>
          </Card>
        </Col>
      </Row>
      
      {/* 第二行 */}
      <Row gutter={[16, 16]} className="second-row" style={{ marginTop: 16 }}>
        {/* 活动图表 */}
        <Col xs={24} md={16}>
          <Card 
            title={
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <AreaChartOutlined style={{ marginRight: 8 }} />
                消息活跃度趋势
              </div>
            }
            bordered={false}
            style={{boxShadow: '0 2px 8px rgba(0,0,0,0.08)'}}
          >
            <Skeleton loading={loading} active paragraph={{ rows: 5 }}>
              <div style={{ height: 250 }}>
                <ResponsiveContainer width="100%" height="100%">
                  <AreaChart
                    data={activityData}
                    margin={{ top: 10, right: 30, left: 0, bottom: 0 }}
                  >
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="date" />
                    <YAxis />
                    <RechartsTooltip />
                    <Area 
                      type="monotone" 
                      dataKey="sent" 
                      stackId="1"
                      stroke="#8884d8" 
                      fill="#8884d8" 
                      name="发送消息"
                    />
                    <Area 
                      type="monotone" 
                      dataKey="received" 
                      stackId="1"
                      stroke="#82ca9d" 
                      fill="#82ca9d" 
                      name="接收消息"
                    />
                  </AreaChart>
                </ResponsiveContainer>
              </div>
            </Skeleton>
          </Card>
        </Col>
        
        {/* WhatsApp连接状态 */}
        <Col xs={24} md={8}>
          <Card
            title={
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <LinkOutlined style={{ marginRight: 8 }} />
                连接状态
              </div>
            }
            extra={<Button type="link" onClick={() => navigate('/connect')}>管理连接</Button>}
            className="status-card"
            loading={loading}
            bordered={false}
            style={{boxShadow: '0 2px 8px rgba(0,0,0,0.08)', marginBottom: 16}}
          >
            {getConnectionStatusContent()}
          </Card>
          
          {/* 响应指标 */}
          <Card
            title={
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <PieChartOutlined style={{ marginRight: 8 }} />
                响应指标
              </div>
            }
            bordered={false}
            style={{boxShadow: '0 2px 8px rgba(0,0,0,0.08)'}}
          >
            <Skeleton loading={loading} active paragraph={{ rows: 2 }}>
              <div>
                <Statistic
                  title="平均响应时间"
                  value={stats.avgResponseTime}
                  suffix="分钟"
                  valueStyle={{ color: '#1890ff' }}
                />
                <div style={{ marginTop: 16 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 5 }}>
                    <Text>响应率</Text>
                    <Text>{stats.responseRate}%</Text>
                  </div>
                  <Progress percent={stats.responseRate} status="active" strokeColor="#1890ff" />
                </div>
              </div>
            </Skeleton>
          </Card>
        </Col>
      </Row>
      
      {/* 最近联系人 */}
      <Card 
        title={
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <TeamOutlined style={{ marginRight: 8 }} />
            最近联系人
          </div>
        }
        extra={<Button type="link" onClick={() => navigate('/chats')}>查看全部</Button>}
        className="recent-contacts-card"
        style={{ marginTop: 16, boxShadow: '0 2px 8px rgba(0,0,0,0.08)' }}
        bordered={false}
      >
        <Table
          columns={columns}
          dataSource={recentContacts}
          rowKey="id"
          loading={loading}
          pagination={false}
          className="contacts-table"
          rowClassName={record => record.unread > 0 ? 'unread-row' : ''}
        />
      </Card>
    </div>
  );
};

export default Dashboard; 